package com.tao.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tao.common.pojo.Result;
import com.tao.common.utils.JWTUtils;
//import com.tao.gateway.properties.AuthWhiteName;
import com.tao.gateway.properties.AuthWhiteName;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    // 白名单设置, 登录和注册页面
//    private List<String> whiteNames = List.of("/user/login", "/user/register");

    @Autowired
    AuthWhiteName authWhiteName;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 配置白名单, 如果请求为白名单就放行
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        log.info("校验是否放行, path: " + path);
        log.info("url: {}", authWhiteName.getUrl());
        if(match(authWhiteName.getUrl(), path)) {
//        if(!whiteNames.contains(path)){
            // 如果不是登录或者注册就放行
            return chain.filter(exchange);
        }

        //从header中获取token
        String userToken = request.getHeaders().getFirst("user_token");
        log.info("从header中获取到token: {}", userToken);
        if(!StringUtils.hasLength(userToken)) {
            log.info("令牌为空");
            return unauthorizeResponse(exchange, "令牌为空");
        }


        //验证用户token
        Claims claims = JWTUtils.parseJWT(userToken);
        if (claims == null){
            log.info("令牌验证失败");
            return unauthorizeResponse(exchange, "令牌验证失败");
        }

        return chain.filter(exchange);
    }

    private boolean match(List<String> url, String path) {
        // 白名单为空
        if(url == null || url.size() == 0) {
            return false;
        }
        // 检验是否在白名单中
        return url.contains(path);
    }

    @SneakyThrows
    private Mono<Void> unauthorizeResponse(ServerWebExchange exchange, String errMsg) {
        // 日志
        log.error("[用户认证失败], url: {}", exchange.getRequest().getURI().getPath());
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应码 401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 设置返回的类型, 设置成 json
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        // 创建返回对象
        Result result = Result.fail(errMsg);
        // 将返回对象, 进行转换, 然后返回
        DataBuffer dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));

        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
